/*
 * sht20.c
 *
 *  Created on: May 20, 2025
 *      Author: zyw
 */


#include"sht20.h"

#define SHT20_I2C_ADDRESS  0x40




static void sht20_SendCmd(uint8_t cmd){
	HAL_I2C_Master_Transmit(&hi2c1, SHT20_I2C_ADDRESS,&cmd, 1, HAL_MAX_DELAY);
}

static void sht20_ReceiveData(uint8_t *receivedata){
	HAL_I2C_Master_Receive(&hi2c1, SHT20_I2C_ADDRESS, receivedata, 3, HAL_MAX_DELAY);
}

static void soft_reset(){
	sht20_SendCmd(0xFE);
}

//通过校验返回1，不通过返回0
static uint8_t sht20_checkcrc(uint8_t  *receivedata,uint8_t length,uint8_t checksum){
	return 1;
}



//hold master   T:0xE3  RH:0xE5
//no hold master   T:0xF3  RH:0xF5
//返回值是经过移位处理过后的二进制数，后续经过等式变换即可获得最终所求
static uint16_t sht20_read(uint8_t cmd,uint8_t * receivedata,uint16_t *data){
	soft_reset();
	sht20_SendCmd(cmd);
	sht20_ReceiveData(receivedata);

	uint8_t checksum;
	*data = ((uint16_t)receivedata[0]<<6)+(((uint16_t)receivedata[1]&0xFC)>>2);
	checksum = receivedata[2];

	if(!sht20_checkcrc(receivedata,2,checksum))
			return -1;
	return 0;
}

//0:hold master   1:no hold  master
void sht20_sample(float * tem,float * RH,uint8_t state){
	uint16_t data;
	uint8_t receivedata[10] = {0};

	if(state == 0){
		sht20_read(0xE3,receivedata,&data);
		*tem = -46.85 + 175.72*1.0*data/(2<<16);
		sht20_read(0xE5,receivedata,&data);
		*RH = -6+125*1.0*data/(2<<16);
	}
	else{
		sht20_read(0xF3,receivedata,&data);
		*tem = -46.85 + 175.72*1.0*data/(2<<16);
		sht20_read(0xF5,receivedata,&data);
		*RH = -6+125*1.0*data/(2<<16);
	}
}



